package com.kelaite.procurement.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.constants.MessageStatusEnum;
import com.kelaite.procurement.entity.TMessage;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.repository.MessageRepository;
import com.kelaite.procurement.service.MessageService;

@Service
@Transactional
public class MessageServiceImpl implements MessageService{
  
	@Autowired
	private MessageRepository messageRepository; 
	
	@PersistenceContext
	private EntityManager em;
	
	@Override
	public TMessage save(TMessage persistence) {
		return this.messageRepository.save(persistence);
	}

	@Override
	public TMessage getObject(Long id) {
		return this.messageRepository.findOne(id);
	}

	@Override
	public List<TMessage> getAll() {
		return this.messageRepository.findAll();
	}

	@Override
	public void deleteByObject(TMessage persistence) {
		this.messageRepository.delete(persistence);
	}

	@Override
	public void deleteByPrimaryKey(Long id) {
		this.messageRepository.delete(id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<TMessage> getByProperty(String property, Object value) {
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TMessage.class).add(Restrictions.eq(property, value))
				.addOrder(Order.desc("id"));
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<TMessage> getUndeletedMessage(TUser user){
		List<TMessage> messageList = new ArrayList<TMessage>();
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TMessage.class)
				.add(Restrictions.eq("tReceiver", user))
				.add(Restrictions.eq("isDeleted", Constants.USER_MESSAGE_UNDELETED))
				.addOrder(Order.desc("id"));
		messageList = criteria.list();
		return messageList;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<TMessage> getUnReadMessage(TUser user){
		List<TMessage> messageList = new ArrayList<TMessage>();
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TMessage.class)
				.add(Restrictions.eq("tReceiver", user))
				.add(Restrictions.eq("readStatus", MessageStatusEnum.UNREADE.getVal()))
				.addOrder(Order.desc("id"));
		messageList = criteria.list();
		return messageList;
	}
	
}
